package Servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import utilidades.Validador;

/**
 * Servlet implementation class Logout
 */
@WebServlet("/Logout")
public class Logout extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ServletContext sc;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Logout() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void init(ServletConfig config) throws ServletException{
		
		super.init(config);
		sc = getServletContext();
		
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try{
			HttpSession session = request.getSession(true);
			
			Validador val = new Validador(sc);
			boolean respuesta = false;
			
			String uid 	= (String) session.getAttribute("user");
			String pass = (String) session.getAttribute("pass");
			
			//TODO Capturar error de validacion
			respuesta = val.validar(uid, pass);
			
			PrintWriter out;
			out = response.getWriter();
			
			if(respuesta){
				response.setHeader("Cache-Control", "no-cache, no-store");
				response.setHeader("Pragma", "no-cache"); 
				
				session.invalidate();
				 
				response.sendRedirect(request.getContextPath() + "/index.html");
				
			}
			else{
				//TODO Servir página de error
			}
		}
		catch(Exception e){
			response.setHeader("Cache-Control", "no-cache, no-store");
			response.setHeader("Pragma", "no-cache"); 
						 
			response.sendRedirect(request.getContextPath() + "/ErrorPages/unknow.html");
		}
	}

}
